package com.zhangzhan.gulimallsearch.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.zhangzhan.gulimallcommcon.tos.es.SkuEsModel;
import com.zhangzhan.gulimallsearch.config.ElasticSearchConfig;
import com.zhangzhan.gulimallsearch.constant.EsConstant;
import com.zhangzhan.gulimallsearch.service.SaveSearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/6/20 23:00
 */
@Service("saveSearchService")
@Slf4j
public class SaveSearchServiceImpl implements SaveSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * @param skuEsModels
     * @return boolean
     * @description 保存商品信息
     * @author zhangyiheng
     * @date 2024/6/20 23:02
     */
    @Override
    public Map<String,Object> saveProduct(List<SkuEsModel> skuEsModels) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {

            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());

            String modelJson = JSON.toJSONString(skuEsModel);
            indexRequest.source(modelJson, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }


        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);


        boolean failures = bulk.hasFailures();

        List<String> errIds = Arrays.stream(bulk.getItems()).map(po -> {
            BulkItemResponse.Failure failure = po.getFailure();
            if (!Objects.isNull(failure)) {
                return failure.getId();
            }
            return null;
        }).toList();

        if (CollUtil.isNotEmpty(errIds)&& !errIds.isEmpty()){
            errIds = errIds.stream().filter(Objects::nonNull).toList();
        }


        return  Map.of("failures",failures,"errIds",errIds);
    }
}
